package megatron.com.megatron;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alivc.live.pusher.AlivcLivePusher;

import java.lang.reflect.Field;
import java.util.List;

public class VideoRecordSmallView extends LinearLayout {

    public static int viewWidth;

    public static int viewHeight;

    private static int statusBarHeight;

    private WindowManager windowManager;

    private WindowManager.LayoutParams mParams;

    private AlivcLivePusher mAlivcLivePusher = null;

    private float xInScreen;

    private float yInScreen;

    private float xDownInScreen;

    private float yDownInScreen;

    private float xInView;

    private float yInView;

//    private TextView mBack;
//    private TextView mPrivacy;
//    private TextView mMic;

    private boolean mPrivacyOn = false;
    private boolean mCameraOn = false;
    private boolean mMuteOn = false;
    private boolean mMixOn = false;

    private Context mContext;
    private int mCurrentTaskId;
    private View mRootView = null;
    private VideoRecordViewManager.CameraOn mCameraOnListener = null;

    private boolean mCameraOpenByMix = false;
    private ImageView record_status_img;
    private TextView record_status_text;
    private ImageView record_close;
    int time=0;
    Handler mHandler = new Handler();
    private MyRunnable mRunnable;
    boolean isRun = true;

    public VideoRecordSmallView(Context context, int currentTaskId) {
        super(context);
        this.mContext = context;
        this.mCurrentTaskId = currentTaskId;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mRootView = LayoutInflater.from(context).inflate(R.layout.record_widget, this);
        View view = findViewById(R.id.record_window_layout);
//        mBack = (TextView) view.findViewById(R.id.back);
//        mPrivacy = (TextView) view.findViewById(R.id.privacy);
//        mMic = (TextView) view.findViewById(R.id.mic);
//        mBack.setOnClickListener(mOnClickListener);
//        mPrivacy.setOnClickListener(mOnClickListener);
//        mMic.setOnClickListener(mOnClickListener);

        record_status_img = (ImageView) view.findViewById(R.id.record_status_img);
        record_status_text = (TextView) view.findViewById(R.id.record_status_text);
        record_close = (ImageView) view.findViewById(R.id.record_close);

        record_close.setOnClickListener(mOnClickListener);
        record_status_text.setOnClickListener(mOnClickListener);

        viewWidth = view.getLayoutParams().width;
        viewHeight = view.getLayoutParams().height;

        record_status_img.setBackgroundResource(R.mipmap.work_stop);
        if (mRunnable == null) {
            mRunnable = new MyRunnable();
            mHandler.postDelayed(mRunnable, 0);
        }

        if (mAlivcLivePusher != null) {
            try {
                mAlivcLivePusher.setMute(false);
             } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void setVisible(boolean visible) {
        if (visible) {
            mRootView.setVisibility(VISIBLE);
        } else {
            mRootView.setVisibility(INVISIBLE);
        }
    }

    public void setTimeRun(){
        isRun = !isRun;


    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xInView = event.getX();
                yInView = event.getY();
                xDownInScreen = event.getRawX();
                yDownInScreen = event.getRawY() - getStatusBarHeight();
                xInScreen = event.getRawX();
                yInScreen = event.getRawY() - getStatusBarHeight();
                break;
            case MotionEvent.ACTION_MOVE:
                xInScreen = event.getRawX();
                yInScreen = event.getRawY() - getStatusBarHeight();
                updateViewPosition();
                break;
            case MotionEvent.ACTION_UP:
                if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
                }
                break;
            default:
                break;
        }
        return true;
    }

    public void setParams(AlivcLivePusher pusher, WindowManager.LayoutParams params) {
        mAlivcLivePusher = pusher;
        mParams = params;
    }

    public void setCameraOnListern(VideoRecordViewManager.CameraOn listern) {
        mCameraOnListener = listern;
    }

    /**
     * 更新小悬浮窗在屏幕中的位置。
     */
    private void updateViewPosition() {
        mParams.x = (int) (xInScreen - xInView);
        mParams.y = (int) (yInScreen - yInView);
        windowManager.updateViewLayout(this, mParams);
    }

    /**
     * 用于获取状态栏的高度。
     *
     * @return 返回状态栏高度的像素值。
     */
    private int getStatusBarHeight() {
        if (statusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer) field.get(o);
                statusBarHeight = getResources().getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusBarHeight;
    }

    private boolean IsForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
//            if(id==R.id.record_status_text){
//                if (mAlivcLivePusher != null) {
//                    mMuteOn = !mMuteOn;
//                    try {
//                        mAlivcLivePusher.setMute(mMuteOn);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    if (mMuteOn) {
//                        record_status_img.setBackgroundResource(R.mipmap.work_start);
//                        mHandler.removeCallbacks(mRunnable);
//                        mRunnable = null;
//                    } else {
//                        record_status_img.setBackgroundResource(R.mipmap.work_stop);
//                        if (mRunnable == null) {
//                            mRunnable = new MyRunnable();
//                            mHandler.postDelayed(mRunnable, 0);
//                        }
//                    }
//                }
//            }else
                if(id==R.id.record_close){
                if (mContext != null) {
                    if (!IsForeground(mContext) && mCurrentTaskId != 0) {
                        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
                        if (am != null) {
                            am.moveTaskToFront(mCurrentTaskId, ActivityManager.MOVE_TASK_WITH_HOME);
                        }
                    } else {
                        Intent intent = new Intent(mContext, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("cutDown","0");
                        mContext.startActivity(intent);
                    }
                }
            }

//            if (id == R.id.back) {
//                if (mContext != null) {
//                    if (!IsForeground(mContext) && mCurrentTaskId != 0) {
//                        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
//                        if (am != null) {
//                            am.moveTaskToFront(mCurrentTaskId, ActivityManager.MOVE_TASK_WITH_HOME);
//                        }
//                    } else {
//                        Intent intent = new Intent(mContext, VideoRecordConfigActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        mContext.startActivity(intent);
//                    }
//                }
//            } else if (id == R.id.privacy) {
//                if (mAlivcLivePusher != null && mPrivacyOn) {
//                    try {
//                        mAlivcLivePusher.resumeScreenCapture();
//                    } catch (Exception e) {
//
//                    }
//                    mPrivacy.setText(R.string.privacy_on);
//                    mPrivacyOn = false;
//                } else if (mAlivcLivePusher != null && !mPrivacyOn) {
//                    try {
//                        mAlivcLivePusher.pauseScreenCapture();
//                    } catch (Exception e) {
//
//                    }
//                    mPrivacy.setText(R.string.privacy_off);
//                    mPrivacyOn = true;
//                }
//            } else if (id == R.id.mic) {
//                if (mAlivcLivePusher != null) {
//                    mMuteOn = !mMuteOn;
//                    try {
//                        mAlivcLivePusher.setMute(mMuteOn);
//                    } catch (Exception e) {
//
//                    }
//                    if (mMuteOn) {
//                        mMic.setText(R.string.mic_on);
//                    } else {
//                        mMic.setText(R.string.mic_off);
//                    }
//                }
//
//            }
        }
    };

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            if(isRun){
                time++;
                record_status_text.setText(String.format("%02d:%02d", time / 60 % 60, time % 60));

            }
            mHandler.postDelayed(this, 1000);
        }
    }
}


